<template>
  <view class="container">
    <view class="cd-bg">
      <!-- 基本信息 -->
      <view class="cd-title">
        <uni-row>
          <uni-col :span="20">
            <view class="param">基本信息</view>
          </uni-col>
          <uni-col :span="4">
            <view class="param" v-if="detail.sta == 0 && detail.chexiao == 0">
              <uni-tag text="审核" type="warning"></uni-tag>
            </view>
            <view class="param" v-if="detail.sta == 1 && detail.chexiao == 0">
              <uni-tag text="通过" type="primary"></uni-tag>
            </view>
            <view class="param" v-if="detail.sta == 2 && detail.chexiao == 0">
              <uni-tag text="拒绝" type="error"></uni-tag>
            </view>
            <view class="param" v-if="detail.chexiao == 1">
              <uni-tag text="撤销" type="default"></uni-tag>
            </view>
          </uni-col>
        </uni-row>
      </view>
      <view class="cd-body">
        <view class="param">
          <b>申请类型：</b>
          {{ detail.type == 1 ? '外单位人员工作餐' : '本单位人员工作餐' }}
        </view>
        <view class="param">
          <b>申请人：</b>
          {{ detail.createBy }}
        </view>
        <view class="param">
          <b>申请时间：</b>
          {{ getFormatedTimeStr(detail.createTime) }}
        </view>
      </view>

      <!-- 特殊参数 -->
      <view class="cd-line">
        <view class="param">申请信息</view>
      </view>
      <view class="cd-body">
        <view class="param" v-if="detail.type == 1">
          <b>来客单位：</b>
          {{ detail.unit }}
        </view>
        <view class="param" v-if="detail.type == 1">
          <b>来客人数：</b>
          {{ detail.number }}
        </view>
        <view class="param">
          <b>{{ people[detail.type - 1] }}：</b>
          {{ nameList }}
        </view>
        <view class="param">
          <b>用餐标准：</b>
          {{ detail.haveDinnerStandard }}元
        </view>
        <view class="param">
          <b>{{ times[detail.type - 1] }}：</b>
          {{ detail.receptionTime }}
        </view>
        <view class="param" v-if="detail.type == 2">
          <b>就餐地点：</b>
          {{ detail.location }}
        </view>
        <view class="param">
          <b>{{ shiyou[detail.type - 1] }}：</b>
          {{ detail.content }}
        </view>
      </view>

      <!-- 相关附件 -->
      <view class="cd-line">
        <view class="param">
          <b>相关附件</b>
        </view>
      </view>
      <view class="cd-body">
        <!-- 附件 -->

        <view class="param">
          <b>附件：</b>
        </view>
        <view v-for="(it, idx) in detail.url" :key="idx">
          <view @click="prevFileClick(it)" class="file_list_item">
            <view>
              <i class="iconfont icon-24gf-folderOpen" style="color: #3c95ff"></i>
              {{ it.name }}
            </view>
          </view>
          <!-- <view class="file_list_item">
              <uni-link
                :href="it.url"
                :text="it.name"
                fontSize="16"
                color="royalblue"
                showUnderLine="false"
              ></uni-link>
            </view>-->
        </view>
      </view>

      <!-- 审核进度 -->
      <view class="cd-line">
        <view class="param">
          <b>审核进度</b>
        </view>
      </view>

      <view class="cd-body">
        <view v-for="(audi, idx, id) in detail.approvalProcessDataBeanMap" :key="idx">
          <uni-row>
            <uni-col :span="24">
              <view class="step-arrow">
                <uni-icons type="bottom" size="30" color="#a5eaff"></uni-icons>
              </view>
            </uni-col>
          </uni-row>
          <view class="step">
            <view class="step-title">
              <uni-row>
                <uni-col :span="8">
                  <view class="step-title-left">{{ audi.name }}</view>
                </uni-col>
                <uni-col :span="8">
                  <view class="step-title-center">
                    <uni-tag text="未审核" size="mini" type="default" v-if="audi.sta == 0"></uni-tag>
                    <uni-tag text="同意" size="mini" type="primary" v-if="audi.sta == 1"></uni-tag>
                    <uni-tag text="拒绝" size="mini" type="error" v-if="audi.sta == 2"></uni-tag>
                    <uni-tag text="撤销" size="mini" type="default" v-if="audi.sta == 3"></uni-tag>
                  </view>
                </uni-col>
                <uni-col :span="8">
                  <view class="step-title-right">{{ audi.stepName }}</view>
                </uni-col>
              </uni-row>
            </view>
            <view class="step-info">
              <uni-row>
                <uni-col :span="16" v-if="audi.sta > 0 && audi.msg == ''">
                  <view class="msg">
                    <b>意见：</b>无
                  </view>
                </uni-col>
                <uni-col :span="16" v-if="audi.sta > 0 && audi.msg != ''">
                  <view class="msg">
                    <b>意见：</b>
                    {{ audi.msg }}
                  </view>
                </uni-col>
                <uni-col :span="8" v-if="audi.sta > 0">
                  <view class="img-qm">
                    <image :src="audi.signimg" />
                  </view>
                </uni-col>
              </uni-row>
            </view>
            <view class="step-footer">
              <uni-row>
                <uni-col :span="24" v-if="audi.sta > 0">
                  <view class="step-footer-right">{{ getFormatedTimeStr(audi.ts) }}</view>
                </uni-col>
              </uni-row>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view style="padding: 30px;"></view>
      <view class="cd-footer" v-if="see == 1 && isMyAgree() == 1">
        <button @click="clickAudit(0)" type="primary">审批</button>
      </view>
      <view class="cd-footer" v-if="see == 1 && isMyAgree() == 1">
        <button @click="revert()" type="warn">撤销</button>
      </view>

      <view class="cd-footer" v-if="detail.sta == 1">
        <button @click="clickShoucang" type="warn">{{ shoucangBtnStr() }}</button>
      </view>
    </view>
  </view>
</template>
  
<script>
import { websock } from "../../net/websock";
import {
  prevFile // 预览普通文件
} from "../../utils/preview.js";
import { getgongzuocan } from "../../net/gongzuocan";
import moment from "moment";
import { shenpigongzuocan } from "../../net/gongzuocan";
export default {
  data() {
    return {
      times: ["接待时间", "就餐时间"],
      people: ["陪同人员", "就餐人员"],
      shiyou: ["接待事由", "申请事由"],
      nameList: [],
      id: 0,
      taskid: 0,
      see: 0,
      itemsd: "",
      itemssd: "",
      approval: [],
      contents: {},
      taskInfo: {},
      detail: {},
      userInfo: {},
      approvalProcessDataBeanMaps: {}
    };
  },
  async onReady() {
    try {
      this.userInfo = await websock.getUserInfo();
    } catch (e) {
      uni.showToast({
        title: e.message
      });
    }
  },

  async onLoad(params) {
    //获取所有人
    let arr = []
    const data = await websock.getContactList()
    console.log(data);
    data.forEach(item => {
      if (item.userList) {
        item.userList.forEach(items => {
          arr.push({ uid: items.uid, name: items.name })
        })
      }
    })
    console.log(params);
    if (params.content) {
      this.itemssd = params.itemss;
      this.contents = JSON.parse(params.content);
      console.log(JSON.parse(params.content));
      let chakan = JSON.parse(params.content);
      this.detail.auditors = chakan;

      this.detail.type = chakan.type; //类型
      if (this.detail.type == 1) {
        this.detail.number = chakan.number; //人数
        this.detail.unit = chakan.unit; //单位
      } else {
        this.detail.location = chakan.location; //单位
      }
      this.detail.createBy = chakan.createBy; //申请人
      this.detail.createTime = chakan.createTime; //申请时间
      this.detail.accompanyIds = chakan.accompanyIds; //陪同或就餐人员
      let name = []
      chakan.accompanyIds.split(',').forEach(item => {
        arr.forEach(data => {
          if (item == data.uid) {
            name.push(data.name)
          }
        })
      })
      console.log(name);
      this.nameList = name.join(',')//显示用餐人员或陪同 人员名称
      this.detail.haveDinnerStandard = chakan.haveDinnerStandard; //餐标
      this.detail.receptionTime = chakan.receptionTime; //接待或就餐时间
      this.detail.content = chakan.content; //申请或接待事由
      this.detail.url = chakan.accessoryBeans; //附件
      this.approvalProcessDataBeanMaps = chakan.approvalProcessDataBeanMap;
      this.detail.approvalProcessDataBeanMap = Array.from(
        Object.values(chakan.approvalProcessDataBeanMap),
        x => x
      );
      this.approval = Array.from(
        Object.values(chakan.approvalProcessDataBeanMap),
        x => x
      );
      console.log(this.detail.approvalProcessDataBeanMap);
      // let arr = [];
      // if (this.itemssd == 1) {
      //   this.detail.approvalProcessDataBeanMap.forEach(datas => {
      //     console.log(datas);
      //     if (datas.sta === 2 || datas.sta === 3) {
      //       arr.push(datas);
      //     } else {
      //       arr = this.detail.approvalProcessDataBeanMap;
      //     }
      //   });
      // }
      // this.detail.approvalProcessDataBeanMap = arr;
      // console.log(arr);

      // for (let key in this.detail.auditors) {
      //   websock
      //     .getUserInfoByUid({
      //       uid: this.detail.auditors.uid
      //     })
      //     .then(res => {
      //       this.detail.auditors.name = res.name;
      //       this.detail.auditors.signimg = res.signimg;
      //     });
      // }
    } else {
      this.id = params.id;
      this.taskid = params.taskid;
      this.see = params.see || 0;
      this.itemsd = params.items;
      console.log("onload", params);

      this.getInfo();
      if (!params.ta) {
        this.taskInfo = await websock.getTaskDetail({ id: params.taskid });
      }
    }
  },
  methods: {
    prevFileClick(item) {
      prevFile(item);
    },
    async getInfo() {
      //获取所有人
      let arr = []
      const data = await websock.getContactList()
      console.log(data);
      data.forEach(item => {
        if (item.userList) {
          item.userList.forEach(items => {
            arr.push({ uid: items.uid, name: items.name })
          })
        }
      })
      console.log(this.id, this.taskid);
      const id = this.id;
      const taskid = this.taskid;
      console.log(id, taskid);
      const res = await getgongzuocan(id);
      console.log(res);
      this.detail = res.data;
      if (this.detail.workingLunch.type == 1) {
        this.detail.number = res.data.workingLunch.number; //人数
        this.detail.unit = res.data.workingLunch.unit; //单位
      } else {
        this.detail.location = res.data.workingLunch.location; //单位
      }
      this.detail.type = res.data.workingLunch.type; //类型
      this.detail.createBy = res.data.workingLunch.createBy; //申请人
      this.detail.createTime = res.data.workingLunch.createTime;
      // this.detail.unit = res.data.workingLunch.unit; 
      this.detail.accompanyIds = res.data.workingLunch.accompanyIds;
      let name = []
      res.data.workingLunch.accompanyIds.split(',').forEach(item => {
        arr.forEach(data => {
          if (item == data.uid) {
            name.push(data.name)
          }
        })
      })
      console.log(name);
      this.nameList = name.join(',')//显示用餐人员或陪同 人员名称
      // this.detail.number = res.data.workingLunch.number; //来文单位
      this.detail.haveDinnerStandard = res.data.workingLunch.haveDinnerStandard;
      this.detail.receptionTime = res.data.workingLunch.receptionTime; //时间
      this.detail.content = res.data.workingLunch.content; //内容
      this.detail.url = res.data.workingLunch.accessoryBeans; //附件
      console.log(res);
      this.approvalProcessDataBeanMaps =
        res.data.workingLunch.approvalProcessDataBeanMap; //附件
      this.detail.approvalProcessDataBeanMap = Array.from(
        Object.values(res.data.workingLunch.approvalProcessDataBeanMap),
        x => x
      );

      this.approval = Array.from(
        Object.values(res.data.workingLunch.approvalProcessDataBeanMap),
        x => x
      );
      console.log(this.approval);
      for (let key in this.detail.auditors) {
        websock
          .getUserInfoByUid({
            uid: this.detail.auditors[key].uid
          })
          .then(res => {
            this.detail.auditors[key].name = res.name;
            this.detail.auditors[key].signimg = res.signimg;
          });
      }
    },

    async clickShoucang() {
      try {
        if (this.detail.shoucang) {
          await websock.cancelShoucang({
            id: this.detail.id,
            typ: 18
          });
          this.detail.shoucang = 0;
        } else {
          await websock.shoucangGongwen({
            id: this.detail.id,
            typ: 18,
            title: this.detail.biaoti,
            content: this.detail.content
          });
          this.detail.shoucang = 1;
        }
      } catch (err) {
        console.error(err);
        uni.showToast({
          title: err.message || "error"
        });
      }
    },
    // 进行审批
    clickAudit(typ) {
      uni.navigateTo({
        url: `/pages/common/audit4?taskid=${this.taskid}&typ=${typ}&id=${this.id
          }&approvalProcessDataBeanMap=${JSON.stringify(
            this.approvalProcessDataBeanMaps
          )}`
      });
    },
    // 判断我是不是审批过
    isMyAgree() {
      let myid = this.userInfo.uid;
      console.log(myid);
      for (let key in this.detail.approvalProcessDataBeanMap) {
        if (
          this.detail.approvalProcessDataBeanMap[key].uid == myid &&
          this.detail.approvalProcessDataBeanMap[key].sta == 0
        ) {
          return 1;
        }
      }
      return 0;
    },
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = "MM-DD HH:mm:ss") {
      return moment(stamp).format(str);
    },

    //点击放大U图片
    showBigImg(imgurl, cur) {
      uni.previewImage({
        current: cur,
        loop: true,
        urls: imgurl
      });
    },
    shoucangBtnStr() {
      if (this.detail.shoucang) return "取消收藏";
      return "收藏";
    },
    async revert() {
      console.log(this.approvalProcessDataBeanMaps);
      this.approvalProcessDataBeanMaps = Array.from(
        Object.values(this.approvalProcessDataBeanMaps),
        x => x
      );
      console.log(this.approvalProcessDataBeanMaps);
      const timestamp = new Date().getTime();
      this.approvalProcessDataBeanMaps.forEach(data => {
        console.log(data.uid);
        console.log(uni.getStorageSync("userInfo").uid);
        if (data.uid == this.taskInfo.uid) {
          data.msg = this.msg;
          data.sta = 3;
          data.ts = timestamp;
        }
      });
      console.log(this.approvalProcessDataBeanMaps);

      let OldObject = this.approvalProcessDataBeanMaps.reduce((o, n, i) => {
        o["auditor" + i] = {
          ts: n.ts,
          msg: n.msg,
          sta: n.sta,
          signimg: n.signimg,
          uid: n.uid,
          stepName: n.stepName,
          name: n.name
        };
        return o;
      }, {});
      console.log(OldObject);
      // 新建事项
      const params = {
        id: this.id,
        taskId: this.taskid,
        approvalProcessDataBeanMap: OldObject
      };
      try {
        await shenpigongzuocan(params);
        uni.$emit("TASK-REVERT", this.taskid);
        setTimeout(
          () =>
            uni.navigateBack({
              delta: 1
            }),
          uni.showToast({
            title: "撤销成功"
          }),
          100
        );
      } catch (err) {
        console.error(err);
      }
    }
  }
};
</script>
  
<style>
@import url("../common/detail.css");
</style>
  